﻿using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ExportAnimWindow : EditorWindow
{
    Vector2 scrollPos = Vector2.zero;
    string path;
    string Path
    {
        get
        {
            return path;
        }
        set
        {
            if (value != path)
            {
                if (directoryPrefabs == null)
                {
                    directoryPrefabs = new List<string>();
                }
                else
                {
                    directoryPrefabs.Clear();
                }
                if (AllAssetPaths == null)
                {
                    AllAssetPaths = new List<string>();
                }
                else
                {
                    AllAssetPaths.Clear();
                }
                path = value;
            }
        }
    }

    string clipPath;//单个动画路径

    static EditorWindow myWindow;
    static List<string> directoryPrefabs;
    static List<string> AllAssetPaths;

    bool showPrefabs = true;

    int replaceModeIndex = -1;
    int ReplaceModeIndex
    {
        get
        {
            return replaceModeIndex;
        }
        set
        {
            if (value != replaceModeIndex)
            {
                if (directoryPrefabs == null)
                {
                    directoryPrefabs = new List<string>();
                }
                else
                {
                    directoryPrefabs.Clear();
                }
                if (AllAssetPaths == null)
                {
                    AllAssetPaths = new List<string>();
                }
                else
                {
                    AllAssetPaths.Clear();
                }
                Path = "";
                replaceModeIndex = value;
            }
        }
    }

    [MenuItem("AnimtionTools/Export")]
    static void Init()
    {
        myWindow = EditorWindow.GetWindow(typeof(ExportAnimWindow));
        directoryPrefabs = new List<string>();
        AllAssetPaths = new List<string>();
        myWindow.minSize = new Vector2(500, 300);
    }

    int targetFrame = 60;

    void OnGUI()
    {
        GetClipPath();
        GetPath();
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("动画导出帧率", GUILayout.Width(100));
        targetFrame = EditorGUILayout.IntField(targetFrame);
        EditorGUILayout.EndHorizontal();

        ReplaceModeIndex = 0;

        scrollPos = EditorGUILayout.BeginScrollView(scrollPos);

        ShowAllPrefabs();
        EditorGUILayout.EndScrollView();
        EditorGUILayout.BeginHorizontal();
        LoadFBX();
        EditorGUILayout.EndHorizontal();
        GeneratePrefab();
    }

    void GetClipPath()
    {
        Event e = Event.current;
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("动画Clip:(拖拽)", GUILayout.Width(100));
        clipPath = GUILayout.TextField(clipPath);
        EditorGUILayout.EndHorizontal();
        if (Event.current.type == EventType.DragExited || Event.current.type == EventType.DragUpdated)
        {
            if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                if (Event.current.type == EventType.DragExited)
                {
                    DragAndDrop.AcceptDrag();
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
                    {
                        clipPath = DragAndDrop.paths[0];
                    }
                }
                e.Use();
            }
            else
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
            }
        }
    }

    void GetPath()
    {
        Event e = Event.current;
        EditorGUILayout.BeginHorizontal();
        GUILayout.Label("资源文件夹:(拖拽)", GUILayout.Width(100));
        Path = GUILayout.TextField(Path);
        if (GUILayout.Button("选择", GUILayout.Width(50)))
        {
            Path = EditorUtility.OpenFolderPanel("选择路径", Application.dataPath, "");
        }
        EditorGUILayout.EndHorizontal();
        if (Event.current.type == EventType.DragExited || Event.current.type == EventType.DragUpdated)
        {
            if (GUILayoutUtility.GetLastRect().Contains(Event.current.mousePosition))
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Link;
                if (Event.current.type == EventType.DragExited)
                {
                    DragAndDrop.AcceptDrag();
                    if (DragAndDrop.paths != null && DragAndDrop.paths.Length > 0)
                    {
                        if (File.Exists(DragAndDrop.paths[0]))
                        {
                            EditorUtility.DisplayDialog("警告", "请拖拽文件夹！", "确定");
                            return;
                        }
                        Path = DragAndDrop.paths[0];
                    }
                }
                e.Use();
            }
            else
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Rejected;
            }
        }
    }
    void ShowAllPrefabs()
    {
        if (directoryPrefabs != null && directoryPrefabs.Count > 0)
        {
            showPrefabs = EditorGUILayout.Foldout(showPrefabs, "显示动画资源");
            if (showPrefabs)
            {
                for (int i = 0; i < directoryPrefabs.Count; i++)
                {
                    int index = i;
                    EditorGUILayout.BeginHorizontal();
                    EditorGUILayout.SelectableLabel($"FBX路径：{directoryPrefabs[index]}");
                    if (GUILayout.Button("查看", GUILayout.Width(60)))
                    {
                        EditorGUIUtility.PingObject(AssetDatabase.LoadAssetAtPath<Object>(directoryPrefabs[index]));
                        Selection.activeGameObject = AssetDatabase.LoadAssetAtPath<Object>(directoryPrefabs[index]) as GameObject;
                    }
                    if (GUILayout.Button("删除", GUILayout.Width(60)))
                    {
                        directoryPrefabs.RemoveAt(index);
                    }
                    EditorGUILayout.EndHorizontal();
                }
            }
            else
            {
                if (GUILayout.Button("清空选择", GUILayout.Width(60)))
                {
                    directoryPrefabs.Clear();
                    AllAssetPaths.Clear();
                    Path = "";
                }
            }
        }
    }

    void GeneratePrefab()
    {
        EditorGUILayout.BeginHorizontal();

        if (GUILayout.Button("导出单个动画"))
        {
            if (string.IsNullOrEmpty(clipPath))
            {
                Debug.LogError("先拖拽动画");
                return;
            }
            AnimationClip clip = AssetDatabase.LoadAssetAtPath<AnimationClip>(clipPath);

            if (clip != null)
                AnimInfoOutput.OutputAnim(clip, targetFrame);
            else
                Debug.LogError("未加载到clip：" + clipPath);

            //string jsonPath = AnimConfig.folderPath + "/" + prefabName + "_trans.json";
            //string json = File.ReadAllText(jsonPath);
            //var animTransformData = JsonUtility.FromJson<AnimTransformData>(json);
            //if (animTransformData != null)
            //{
            //    foreach (var item in animTransformData.transDatas)
            //    {
            //        Debug.Log("frame:" + item.frame + ", position:" + item.position + ", rotation:" + item.rotation);
            //    }
            //}
            //Debug.Log("解析出数据" + animTransformData.length);
        }


        if (GUILayout.Button("导出选择文件夹内动画"))
        {
            AllAssetPaths.Clear();
            if (directoryPrefabs != null)
            {
                directoryPrefabs.Clear();
            }
            else
            {
                directoryPrefabs = new List<string>();
            }
            LoadFBXAuto();

            Debug.Log("开始生成");

            if (directoryPrefabs.Count > 0)
            {
                foreach (var fbxPath in directoryPrefabs)
                {
                    //过滤一些没有位移的动作
                    //string fbxName = System.IO.Path.GetFileNameWithoutExtension(fbxPath);
                    //if (fbxName.Contains("@"))
                    //{
                    //    if (!AllAssetPaths.Contains(fbxPath))
                    //        AllAssetPaths.Add(fbxPath);
                    //}
                    //测试生成所有
                    if (!AllAssetPaths.Contains(fbxPath))
                        AllAssetPaths.Add(fbxPath);
                }
            }

            for (int i = 0; i < AllAssetPaths.Count; i++)
            {
                AnimationClip clip = AssetDatabase.LoadAssetAtPath(AllAssetPaths[i], typeof(AnimationClip)) as AnimationClip;
                if (clip != null)
                {
                    AnimInfoOutput.OutputAnim(clip, targetFrame);
                }
                else
                {
                    Debug.LogError("未加载到clip：" + AllAssetPaths[i]);
                }
            }
        }

        EditorGUILayout.EndHorizontal();

    }

    void LoadFBX()
    {
        if (GUILayout.Button("加载FBX"))
        {
            if (!string.IsNullOrEmpty(Path))
            {
                LoadFBXAuto();
            }
        }
    }
    void LoadFBXAuto()
    {
        DirectoryInfo direction = new DirectoryInfo(Path);
        FileInfo[] files = direction.GetFiles("*.fbx", SearchOption.AllDirectories);
        for (int i = 0; i < files.Length; i++)
        {
            int startindex = files[i].FullName.IndexOf("Assets");
            string unityPath = files[i].FullName.Substring(startindex);
            if (!directoryPrefabs.Contains(unityPath))
            {
                directoryPrefabs.Add(unityPath);
            }
        }
    }
}
